package cn.mjnxin.iot.client.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.mjnxin.iot.base.concurrent.ThreadFactoryImpl;
import cn.mjnxin.iot.base.domain.ChannelData;
import cn.mjnxin.iot.base.process.IWorker;
import io.netty.channel.Channel;

/**
 * 上行报文发送工
 * @Description: 前置报文实际发送终端
 * @author CLG 2023年10月10日
 * @version V1.0.0
 */
public class Terminal2GateWorker implements IWorker{
	private final int                poolSize;
	private final ExecutorService    exService;
	public Terminal2GateWorker(int poolSize) {
		super();
		this.poolSize = poolSize;
		this.exService = Executors.newFixedThreadPool(poolSize,new ThreadFactoryImpl("msgTransWorker_UP_", false));
	}

	public void run() {
		for (int i=0 ; i < poolSize ; i++ ){
			exService.execute(new Runnable() {
				@Override
				public void run() {
					while(true){
						send();
					}
				}

			});
		}
	}

	private void send() {
		try {
			ChannelData channelData = TerminalTest.up2GateQueue.take();
			if(channelData == null){
				System.out.println("设备与网关断连，无法发送报文");
				return;
			}
			Channel channel = TerminalTest.channel;
		    channel.writeAndFlush(channelData);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void start() throws Exception {
		new Thread(this).start();
	}
}
